package scripts;

import api.AddUserApi;
import api.CommonApi;
import api.LoginApi;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.*;
import org.uncommons.reportng.HTMLReporter;
import util.AssertUtil;
import util.DBUtil;
import util.ResponseData;
import util.TestDataUtil;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Random;
@Listeners({HTMLReporter.class})
public class TestAddUser {
    private static final Logger logger= LoggerFactory.getLogger(TestAddUser.class);
    private static final AddUserApi addUserApi=new AddUserApi();
    private static final CommonApi commonApi=new CommonApi();
    private static final LoginApi loginApi=new LoginApi();
    @BeforeMethod
    public static void clear_data() throws SQLException, ClassNotFoundException {
        String sql1="DELETE from mb_member where name=\"tom0002\" or phone=\"18862223423\";";
        String sql2="DELETE from mb_member_info where member_id in(select m.id from mb_member m WHERE m.name=\"tom0002\" or m.phone=\"18862223423\");";
        DBUtil.execute(sql2);
        DBUtil.execute(sql1);
    }
    @DataProvider
    public Object[][] build_data() throws IOException {
//        String file = FileUtils.readFileToString(new File("./data/adduser.json"), "utf-8");
//        JSONArray jsonArray= JSONArray.parseArray(file);
//        Object[][] test_data=new Object[jsonArray.size()][];
//        for(int i=0;i< jsonArray.size();i++){
//            JSONObject jsonObject=jsonArray.getJSONObject(i);
//            test_data[i] =new Object[]{
//                    jsonObject.get("name"),jsonObject.get("phone"),jsonObject.get("pwd"),
//                    jsonObject.get("rePwd"),jsonObject.getIntValue("role"),jsonObject.getIntValue("code"),
//                    jsonObject.getIntValue("body_code"),jsonObject.get("description")
//            };
//        }
        String data="name,phone,pwd,rePwd,role,code,body_code,description";
        Object[][] test_data = TestDataUtil.build_data("adduser.json", data);
        logger.info("test_data={}", Arrays.deepToString(test_data));
        return test_data;

    }
    @BeforeClass
    public static void before() throws IOException, URISyntaxException {
        commonApi.get_verify(String.valueOf(new Random().nextDouble()));
        loginApi.login("admin","12345678","8888");
    }
    @Test(dataProvider = "build_data")
    public static void add_user(String name,String phone,String pwd,String rePwd,int role,int code,int body_code,String description) throws IOException, URISyntaxException {
        ResponseData responseData = addUserApi.add_user(name,phone,pwd,rePwd,role);
        AssertUtil.assertCommon(responseData,code,body_code,description);
    }
}
